redux-thunks
Simple thunk creator for redux.
This is meant to smooth over the use of redux-thunk and redux-actions.
Installation
$ yarn add redux-thunks redux-thunk
or
$ npm install --save redux-thunks redux-thunk
Usage
This module is simply syntactic sugar for using redux-thunk
with redux-actions
. As such, it requires that you use the redux-thunk middleware.
Add redux-thunk middleware
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Action definition
import { createAction, handleAction } from 'redux-actions';
import { createThunk } from 'redux-thunks';
export const setAmount = createAction('SET_AMOUNT');
export const incrementAsync = createThunk('INCREMENT_ASYNC', ({ dispatch, getState }, amount) => {
doAsyncMath(getState(), amount).then(val => dispatch(setAmount(val)));
});
export default handleAction(setAmount, (state, payload) => payload, 0);
The context also receives the type name that you gave the thunk, which is useful to using createAction
inside of the handler function, so that the action type only needs to be defined once, like so:
import { createAction, handleAction } from 'redux-actions';
import { createThunk } from 'redux-thunks';
export const resetAmountAsync = createThunk('RESET_AMOUNT', ({ dispatch, type }) => {
const action = createAction(type);
fetchAsyncValue().then(val => dispatch(action(val)));
});
export default handleAction(resetAmountAsync, (state, payload) => payload, 0);
Use in component/container
dispatch(incrementAsync, 10);
dispatch(resetAmountAsync);
API
createThunk
createThunk('type', ({ dispatch, getState, type }, [...args]))
The syntax is very similar to that of createAction
, and it smooths over the differences by similarly exposing a toString
method on the thunk creator.
createThunk
takes two arguments, a type name, and a function to execute when the action is dispatched. The first argument of the function will be a context object, with the following properties:
name | description |
---|
dispatch | Provided directly from redux-thunk , used to dispatch other actions |
getState | Provided directly from redux-thunk , used to reach the current state |
type | The type name of the action that was passed in as the first argument |
Any additional arguments will be anything specified at the dispatch call site. It's expected that at least one other action will be dispatched from the handler function.
License
MIT © w33ble